<?php
/**
 * Created by PhpStorm.
 * User: MrDong
 * Date: 2020/6/10
 * Time: 9:44
 */

namespace frontend\controllers;

use common\models\Banner;
use common\models\CarServices;
use common\models\DiscountCoupon;
use common\models\FileModel;
use common\models\SetMeal;
use common\models\SetMealOrder;
use common\models\SystemSet;
use frontend\models\SetMealSearch;
use yii\rest\Controller;
use yii\web\UploadedFile;
use common\models\Member;
use common\helpers\SendMsgHelper;

class IndexController extends Controller
{

    /**
     * 首页
     * @return array
     */
    public function actionIndex()
    {
        $banner = Banner::find()->where(['status' => 10, 'type' => 1])->all();
        $searchModel         = new SetMealSearch();
        $dataProvider        = $searchModel->search(\Yii::$app->request->queryParams);
        $items               = $dataProvider->getModels();
        foreach ($items as &$item) {
            $item = $this->getStockModel($item);
        }
        return [
            "banner"    => $banner,
            "lists"      => $items,
            "totalPage" => $dataProvider->pagination->getPageCount()
        ];
    }

    /**
     * 套餐详情
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function actionSetMealDetail($id)
    {
        $model = SetMeal::find()->with(["items", "setMealImages"])->where(['id' => $id])->asArray()->one();
        if(!$model) {
            throw new \Exception("数据异常！");
        }
        $model = $this->getStockModel($model);

        //关于这个套餐的所有优惠券
        $coupons = DiscountCoupon::find()->leftJoin("discount_coupon_in_set_meal", "discount_coupon_in_set_meal.discount_coupon_id = discount_coupon.id")->where(['set_meal_id' => $id])->asArray()->all();

        foreach ($coupons as &$coupon) {
            $coupon['start_date'] = date("Y-m-d", $coupon['start_date']);
            $coupon['end_date'] = date("Y-m-d", $coupon['end_date']);
        }

        return [
            "item" => $model,
            "coupons" => $coupons
        ];
    }

    /**
     * 计算今日剩余库存
     * @param $model
     * @return mixed
     */
    protected function getStockModel(&$model)
    {
        //今日上午下单总量
        $amTotalNum = SetMealOrder::find()->where([
            'time_frame' => "上午",
            'sub_date' => date("Y-m-d"),
            'set_meal_id' => $model['id'],
            'is_use' => 0
        ])->andWhere(['status' => SetMealOrder::STATUS_SUCCESS])->sum("num");
        //今日下午下单总量
        $pmTotalNum = SetMealOrder::find()->where([
            'time_frame' => "下午",
            'sub_date' => date("Y-m-d"),
            'set_meal_id' => $model['id'],
            'is_use' => 0
        ])->andWhere(['status' => SetMealOrder::STATUS_SUCCESS])->sum("num");

        //剩余库存
        $amNum = $model['am_stock'] - $amTotalNum;
        $pmNum = $model['pm_stock'] - $pmTotalNum;
        $model['am_stock'] = $amNum < 0 ? 0 : $amNum;
        $model['pm_stock'] = $pmNum < 0 ? 0 : $pmNum;
        return $model;
    }


    /**
     * 车辆服务
     * @return array
     */
    public function actionCarServices()
    {
        $banner = Banner::find()->where(['status' => 10, 'type' => 2])->all();
        $services = CarServices::find()->all();
        return [
          "banner" => $banner,
          "services" => $services,
        ];
    }

    /**
     * 二手车估价banner
     * @return array|\yii\db\ActiveRecord[]
     */
    public function actionCarValuationBanner()
    {
        return  Banner::find()->where(['status' => 10, 'type' => 3])->all();
    }

    /**
     * 系统设置（加盟、合作、客服电话）
     * @return array|\yii\db\ActiveRecord|null
     */
    public function actionSystemSetInfo()
    {
        return SystemSet::find()->one();
    }

    /**
     * 上传图片
     * @return array
     * @throws \Exception
     */
    public function actionUpImg()
    {
        $model       = new FileModel();
        $model->file = UploadedFile::getInstanceByName('file');
        try {
            return $model->upload();
        } catch (\Exception  $e) {
            throw new \Exception($e->getMessage());
        }

    }

    /**
     * 重置密码
     * @return bool
     * @throws \yii\base\Exception
     * @throws \Exception
     */
    public function actionResetPassword()
    {
        $data = \Yii::$app->request->post();
        $model = Member::findOne(['username' => $data['phone']]);

        if(!$model) {
            throw new \Exception("用户不存在！");
        }
        if($data['code'] != \Yii::$app->cache->get($data['phone'])) {
            throw new \Exception("验证码不正确，请重新输入！");
        }

        $model->password = \Yii::$app->security->generatePasswordHash($data['password']);
        $model->updated_at = time();
        if(!$model->save(false)) {
            throw new \Exception("重置异常:" . current($model->getFirstErrors()));
        }
        return true;
    }

}